//
//  TheMenuView.m
//  pritice
//
//  Created by ChuXiang on 16/1/12.
//  Copyright © 2016年 ChuXiang. All rights reserved.
//

#import "TheMenuView.h"
#import "UIView+UIViewAdditions.h"
#import "MenuCollectionViewCell.h"
#import "CXAddAndDeletaView.h"
#import "CXSpecialCollectionViewCell.h"
#define ZERO                    0.0f
#define ONE                     1.0f
#define ANIMATION_DURATION      0.5f

@interface TheMenuView() <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *menuCollection;
@property (nonatomic, strong) UICollectionView *downMenuCollection;
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic,strong) NSIndexPath *end;
@property (nonatomic,assign) NSIndexPath *indext;
@property (nonatomic, strong) CXAddAndDeletaView *addOrDeleteView;
@property (nonatomic, strong) NSMutableArray *downMenuArray;

@property (nonatomic, strong) NSIndexPath *myIndexPath;



@end

static BOOL ButtonHaveEdit = YES;
static NSInteger num = 0;
static NSString *menuCollectionIdentifier = @"MenuCollectionViewCellIdentifier";
static NSString *speacialMenuCollectionIdentifier = @"SpeacialMenuCollectionViewCellIdentifier";
static NSString *downMenuCollectionIdentiifer = @"MenuCollectionViewCellIdentifier1";
static NSString *headViewIdentifier = @"headerView";
static NSString *downHeadViewIdentifier = @"headerView1";

@implementation TheMenuView


- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.array = [NSMutableArray arrayWithCapacity:0];
        self.downMenuArray = [NSMutableArray arrayWithCapacity:0];
        self.myIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        NSMutableArray *downMenuLocalArray =  [self getLocalDataWithWhatSave:@"downMenuCollection"];
        if (downMenuLocalArray) {
            self.downMenuArray = downMenuLocalArray;
        }
        
        UICollectionViewFlowLayout *flowLaout = [[UICollectionViewFlowLayout alloc] init];
        flowLaout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        flowLaout.itemSize = CGSizeMake(self.width / 4 - 10, 30);

        self.menuCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height ) collectionViewLayout:flowLaout];
        self.menuCollection.delegate = self;
        self.menuCollection.dataSource = self;
        [self.menuCollection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headViewIdentifier];
        self.menuCollection.backgroundColor = [UIColor whiteColor];
        UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongGesture:)];
        [self.menuCollection addGestureRecognizer:longPressGesture];
        
        [self.menuCollection registerClass:[MenuCollectionViewCell class] forCellWithReuseIdentifier:menuCollectionIdentifier];
        [self.menuCollection registerClass:[CXSpecialCollectionViewCell class] forCellWithReuseIdentifier:speacialMenuCollectionIdentifier];
        [self addSubview:self.menuCollection];
    
        
        UICollectionViewFlowLayout *flowLaout1 = [[UICollectionViewFlowLayout alloc] init];
        flowLaout1.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        self.downMenuCollection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLaout1];
        self.downMenuCollection.delegate = self;
        self.downMenuCollection.dataSource = self;
        self.downMenuCollection.backgroundColor = [UIColor blueColor];
        [self.downMenuCollection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:downHeadViewIdentifier];
        self.downMenuCollection.backgroundColor = [UIColor whiteColor];
        
        [self.downMenuCollection registerClass:[MenuCollectionViewCell class] forCellWithReuseIdentifier:downMenuCollectionIdentiifer];
        [self addSubview:self.downMenuCollection];
        
    }
    return self;
}

- (void)setDataSource:(NSMutableArray *)dataSource {
    if (_dataSource != dataSource) {
        _dataSource = dataSource;
    }
    [self.array addObject:@"精选"];
    for (int i = 0; i < dataSource.count; i++) {
        CXAddOrDeleteModel *model = dataSource[i];
        [self.array addObject:model.name];
    }
    
    NSMutableArray *getLocalArray = [self getLocalDataWithWhatSave:@"menuColletion"];

    if (getLocalArray) {
        self.array = getLocalArray;
    }
    [self changeCollectionFream];
}

#pragma mark - 手势管理collectionView Item移动
- (void)handleLongGesture:(UILongPressGestureRecognizer *)gesture{
    if (!ButtonHaveEdit) {
        switch (gesture.state) {
            case UIGestureRecognizerStateBegan:
                
                self.indext = [self.menuCollection indexPathForItemAtPoint:[gesture locationInView:self.menuCollection]];
                
                
                [self.menuCollection beginInteractiveMovementForItemAtIndexPath:self.indext];
                break;
            case UIGestureRecognizerStateChanged:
                
                [self.menuCollection updateInteractiveMovementTargetPosition:[gesture locationInView:gesture.view]];
                
                break;
            case UIGestureRecognizerStateEnded:
                
                [self.menuCollection endInteractiveMovement];
                self.end = [self.menuCollection indexPathForItemAtPoint:[gesture locationInView:self.menuCollection]];
                if (self.end.row == 0) {
                    [self.array insertObject:self.array[self.indext.row] atIndex:self.end.row + 1];
                    [self.array removeObjectAtIndex:self.indext.row + 1];
                } else if (self.indext.row > self.end.row) {
                    [self.array insertObject:self.array[self.indext.row] atIndex:self.end.row];
                    [self.array removeObjectAtIndex:self.indext.row + 1];
                } else if (self.indext.row < self.end.row) {
                    [self.array insertObject:self.array[self.indext.row] atIndex:self.end.row + 1];
                    [self.array removeObjectAtIndex:self.indext.row];
                }
                [self.menuCollection reloadData];

                break;
                
            default:
                [self.menuCollection cancelInteractiveMovement];
                
                break;
        }

    }
}



- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if (kind == UICollectionElementKindSectionHeader) {
        if (collectionView == self.menuCollection) {
            UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headViewIdentifier forIndexPath:indexPath];
            [reusableView removeAllSubviews];
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            button.frame = CGRectMake(self.width - 30 , 10, 30, 20);
            [button setImage:[[UIImage imageNamed:@"shangla"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
            [reusableView addSubview:button];
            
            self.addOrDeleteView = [[CXAddAndDeletaView alloc] initWithFrame:CGRectMake(0, 0, self.width - 20, 40)];
            __weak TheMenuView *weakSelf = self;
            _addOrDeleteView.block = ^(BOOL isYes){
                

                ButtonHaveEdit = isYes;
                
                
                if (isYes) {
                    weakSelf.downMenuCollection.alpha = 1;
                    

                }else if (isYes == NO){
                    
                    
                    weakSelf.downMenuCollection.alpha = 0;
 
                }
                
                [weakSelf.menuCollection reloadData];
            };
            [reusableView addSubview:self.addOrDeleteView];
            return reusableView;

        }else {
            UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:downHeadViewIdentifier forIndexPath:indexPath];
            reusableView.frame = CGRectMake(0, 0, self.width, 30);
            reusableView.backgroundColor = [UIColor colorWithRed:214 / 255.0 green:213 / 255.0 blue:183 / 255.0 alpha:1.0];
            [reusableView removeAllSubviews];

            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((self.width) / 25, 0, (self.width - 40) / 2 - 30, 30)];
            label.textAlignment = NSTextAlignmentCenter;
            label.text = @"点击添加更多频道";
            [label setFont:[UIFont fontWithName:@"FZLanTingHei-EL-GBK" size:13]];
            label.textColor = [UIColor blackColor];
            [reusableView addSubview:label];
            
            return reusableView;

        }
    }else{
        UICollectionReusableView *resableviewtow = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath ];
        return resableviewtow;
    }
}


-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return  CGSizeMake(self.width, 40);
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.downMenuCollection) {
        [self.array addObject:self.downMenuArray[indexPath.item]];
        [self saveLocalData:self.array WithWhatSave:@"menuColletion"];
        
        [self.downMenuArray removeObjectAtIndex:indexPath.row];
        [self saveLocalData:self.downMenuArray WithWhatSave:@"downMenuCollecion"];

        [self changeCollectionFream];
    }
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    if (collectionView == self.downMenuCollection) {
        return self.downMenuArray.count;
    }else {
        return self.array.count;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.menuCollection) {
        if (ButtonHaveEdit == YES) {
            
            MenuCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:menuCollectionIdentifier forIndexPath:indexPath];
            [item setTitle:self.array[indexPath.item] withButtonHaveEdit:ButtonHaveEdit];
            return item;
        }else if (ButtonHaveEdit == NO){
            
            CXSpecialCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:speacialMenuCollectionIdentifier forIndexPath:indexPath];
            if (indexPath.item == 0) {
                [item setTitle:self.array[indexPath.item] withIndexPath:@"10"];
            }else {
                [item setTitle:self.array[indexPath.item] withIndexPath:@"9"];
            }
            item.deleteBlock = ^(void){
                [self.downMenuArray addObject:self.array[indexPath.item]];
                [self saveLocalData:self.downMenuArray WithWhatSave:@"downMenuCollecion"];
    
                [self.array removeObjectAtIndex:indexPath.item];
                [self saveLocalData:self.array WithWhatSave:@"menuColletion"];
            
                [self changeCollectionFream];
            };

//            [item setTitle:self.array[indexPath.item] withButtonHaveEdit:ButtonHaveEdit];
            return item;
        }

    }
        MenuCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:downMenuCollectionIdentiifer forIndexPath:indexPath];
        [item setTitle:self.downMenuArray[indexPath.item] withButtonHaveEdit:YES];
        return item;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.width / 4 - 7, 40);
}



#pragma mark - 行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (void)showInView:(UIView *)view{
    self.menuCollection.alpha = ZERO;
    self.downMenuCollection.alpha = ZERO;
    [view addSubview:self.menuCollection];
    [view addSubview:self.downMenuCollection];
    view.backgroundColor = [UIColor whiteColor];
    [UIView animateWithDuration:ANIMATION_DURATION
                     animations:^{
                         self.menuCollection.alpha = ONE;
                         self.downMenuCollection.alpha = ONE;
                     }
                     completion:^(BOOL finished) {}];
}

- (void)hide{
    [UIView animateWithDuration:ANIMATION_DURATION
                     animations:^{
                         self.menuCollection.alpha = ZERO;
                         self.downMenuCollection.alpha = ZERO;
                     }
                     completion:^(BOOL finished) {
                         [self.menuCollection removeFromSuperview];
                         [self.downMenuCollection removeFromSuperview];
                     }];
}

#pragma mark - GetData
- (NSMutableArray *)getLocalDataWithWhatSave:(NSString *)whatCollection{
    if ([whatCollection isEqualToString:@"menuColletion"]) {
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)firstObject];
        NSString *newFielPath = [documentsPath stringByAppendingPathComponent:@"/mydata.txt"];
        NSMutableArray *plistArray = [NSMutableArray arrayWithContentsOfFile:newFielPath];
        
        return plistArray;
    }else {
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)firstObject];
        NSString *newFielPath = [documentsPath stringByAppendingPathComponent:@"/mydownData.txt"];
        NSMutableArray *plistArray = [NSMutableArray arrayWithContentsOfFile:newFielPath];
        
        return plistArray;
    }

}

#pragma mark - SaveData
- (void)saveLocalData:(NSMutableArray *)data WithWhatSave:(NSString *)whatCollection{
    if ([whatCollection isEqualToString:@"menuColletion"]) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [paths lastObject];
        //在文件路径后拼接文件名
        NSString *strPath = [path stringByAppendingString:@"/mydata.txt"];
        [data writeToFile:strPath atomically:YES];

    }else {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [paths lastObject];
        //在文件路径后拼接文件名
        NSString *strPath = [path stringByAppendingString:@"/mydownData.txt"];
        NSLog(@"%@", strPath);
        [data writeToFile:strPath atomically:YES];
    }
}


#pragma mark - ButtonDIdPress
-(void)buttonPress:(UIButton *)sender{


    if (ButtonHaveEdit == NO) {
        [self.addOrDeleteView deleteButtonDidPress:self.addOrDeleteView.deleteButton];
    }

    [self hide];
    
    self.relodataBlock(self.array);
}

#pragma mark - 动态改变DownCollection Fream
- (void)changeCollectionFream {
    if (self.array.count % 4 == 0) {
        num = self.array.count / 4;
    }else {
        num = self.array.count / 4 + 1;
    }
    if (num == 0) {
        num = 1;
    }
    self.downMenuCollection.frame = CGRectMake(0, num * 40 + 90, self.width, self.height - self.menuCollection.height / 2 + 40);
    [self.downMenuCollection reloadData];
    [self.menuCollection reloadData];

}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
